from sanic.views import HTTPMethodView
from sanic.response import text, json
import time
from processing.other_func import ProToken, Sercret_all, Serialization, Random_id, date_format
import json as jn
import re
from processing.comm import sqlPaging, sqlOrder, sqlKeyword, set_status,set_status_number,set_status_None,order_log
from processing.Sql_DataFrom import ProJosn
import requests


class typeAdd(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip

        html_data = request.json

        try:
            if html_data['split'] == ',':
                list1 = str(html_data['categoryName']).split(',')
            elif html_data['split'] == '、':
                list1 = str(html_data['categoryName']).split('、')
            else:
                list1 = [html_data['categoryName']]

            if html_data['grade'] == '':
                grade = 1
            elif html_data['grade'] == '0':
                grade = 2
            else:
                grade = 3
            for i in list1:

                sql = """
                        insert into category(merchant_id,businessId,categoryDesc,categoryName,image,pid,grade,recommend,status,ctime ) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,now())
                    """
                db.insert(sql,(user_id,
                   html_data['businessId'],
                   html_data['categoryDesc'],
                   i,
                   html_data['image'],
                   html_data['pid'] or '0',
                   grade,
                   0,
                   set_status(html_data['status'])
                   ))
            return json({'code': 200, 'message': "添加成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/category/add', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)
class typeEdit(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip

        html_data = request.json

        try:
            sql = """
                    update category set businessId=%s,categoryDesc=%s,categoryName=%s,status=%s,image=%s,ctime=now() where merchant_id=%s and id=%s
                """
            db.update(sql,(
                html_data['businessId'],
                html_data['categoryDesc'],
                html_data['categoryName'],
                set_status(html_data['status']),
                html_data['image'],
                user_id,
                html_data['id']
            ))
            return json({'code': 200,
                        'message': "编辑成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/category/edit', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)

# 20250211改造成回显
class typeList(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表

        client_ip = request.ip
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 10))
        keyword = request.args.get('keyword', '')
        user_id = request.args.get('user_id', '') or request.app.ctx.user_id
        type_id = request.args.get('type_id', '')
        try:
            sql = f"""
                select id,businessId,categoryDesc,categoryName,image,pid,grade,status,ctime from category where merchant_id='{user_id}' and pid!='0'
            """
            tol = f""" SELECT COUNT(*) FROM category where merchant_id='{user_id}' and pid!='0' """

            # if type_id == '':
            #     sql += f" and pid='0' "
            #
            # if type_id:
            #     sql += f" and pid='{type_id}' "

            if keyword:
                sql += f" and  categoryName LIKE '%{keyword}%' "
                tol += f" and  categoryName LIKE '%{keyword}%' "
            tol_data = db.find_one(tol)
            ordersql = sqlOrder(sql)
            group_sql = sqlPaging(pageNum,pageSize,ordersql)
            data = db.find_all(group_sql)
            if data:
                dataList = ProJosn(data, sql, 'sql')
            else:
                dataList = []
            return json({'code': 200,
                        'data':{
                            'list':dataList,
                            'total':tol_data[0]
                        },
                        'message': "请求成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/category/list', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)
class typeDelete(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        try:
            sql = "delete from category where merchant_id=%s and id=%s"

            db.delete(sql, (user_id,int(html_data['id'])))

            return json({'code': 200,
                        'message': "删除成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/category/delete', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)
class typeOption(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 30))
        keyword = request.args.get('keyword', '')
        user_id = request.args.get('user_id', '') or request.app.ctx.user_id
        type_id = request.args.get('type_id', '')

        try:
            sql_1 = f"""
                select id,businessId,categoryDesc,categoryName,image,pid,status,grade,recommend,ctime from category where merchant_id='{user_id}' and pid='0'
            """
            tol = f""" SELECT COUNT(*) FROM category where merchant_id='{user_id}' and pid='0' """
            if keyword:
                sql_1 += f" and  categoryName LIKE '%{keyword}%' "
                tol += f" and  categoryName LIKE '%{keyword}%' "
            tol_data = db.find_one(tol)
            ordersql = sqlOrder(sql_1)
            group_sql = sqlPaging(pageNum, pageSize, ordersql)
            sql_1_data = db.find_all(group_sql)

            if sql_1_data:
                sql_1_data = ProJosn(sql_1_data,sql_1)

                # for i in range(0,len(sql_1_data)):
                #
                sql_2 = f"""
                    select id,businessId,categoryDesc,categoryName,image,pid,grade,status,recommend,ctime from category where merchant_id='{user_id}' and pid!='0'
                """
                sql_2_data = db.find_all(sql_2)
                if sql_2_data:

                    sql_2_data = ProJosn(sql_2_data,sql_2)
                else:
                    sql_2_data = []

                    # for j in range(0,len(sql_1_data[i]['children'])):
                    #
                    #     sql_3 = f"""
                    #         select id,businessId,categoryDesc,categoryName,image,pid,status,ctime from category where merchant_id='{user_id}' and pid='{sql_1_data[i]['children'][j]['id']}'
                    #     """
                    #     sql_3_data = db.find_all(sql_3)
                    #     sql_3_data = ProJosn(sql_3_data, sql_3)
                    #     sql_1_data[i]['children'][j]['children'] = sql_3_data


            else:
                sql_1_data = []

            return json({'code': 200,
                         'message': "请求成功!",
                         'data':{
                             'list':sql_1_data,
                             'total':tol_data[0],
                             'children':sql_2_data
                         }
                         })

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/category/typeOption', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
class typeSetData(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip

        html_data = request.json

        try:
            sql = """
                    update category set recommend=%s,ctime=now() where merchant_id=%s and id=%s
                """
            db.update(sql,(
                html_data['recommend'],
                user_id,
                html_data['id']
            ))
            return json({'code': 200,
                        'message': "设置成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/category/typeSetData', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)

class goodsAdd(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        client_ip = request.ip
        html_data = request.json
        user_id = request.app.ctx.user_id

        try:
            if html_data['businessId'] or html_data['businessId']!=[]:
                for businessId in (html_data['businessId']):
                    goods_id = Random_id(18, "GOODSID")
                    sql = """
                        insert into goods(goodsPrice,goods_status,goodsSkuType,scribePrice,previewUrl,goodsBeginTime,goodsEndingTime,goodsSkuJson,goods_id,goodsName,goods_type,categoryId,businessId,
                            goods_unit,goods_unit_num,goods_code,rotationImgsJson,label_ids,stockNum,goods_number,goods_barCode,goodsWeight,goods_volume,
                            contents,goodsType,distributionType,distributionFee,goods_sales,sort,rewardIntegral,gift_coupons_id,serviceGuarantee_id,member_see,start_shopping,is_limitNum,limitNum
                            ,limitNum_type,is_reservation,reservation_startTime,reservation_endTime,reservation_send_time,is_reservation_endTime,goods_recommend,goods_recommend_id,keywords,goods_introduction,
                            goods_distribution_text,goods_command,goods_recommend_image,merchant_id,ctime
                             ) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now())
                        """
                    db.insert(sql, (
                        (html_data['goodsPrice']),  # dict
                        (html_data['goods_status']),  # dict
                        html_data['goodsSkuType'],  # dict
                        html_data['scribePrice'],  # dict
                        html_data['previewUrl'],  # dict
                        set_status_None(html_data['goodsBeginTime']) or '2000-01-01 00:00:00',
                        set_status_None(html_data['goodsEndingTime']) or '2000-01-01 00:00:00',
                        html_data['goodsSkuJson'],  # dict
                        goods_id,  # str
                        html_data['goodsName'],  # str
                        set_status_None(html_data['goods_type']),  # varchar
                        set_status_None(html_data['categoryId']),  # text
                        businessId,  # text
                        set_status_None(html_data['goods_unit']),  # varchar
                        (html_data['goods_unit_num']),  # varchar
                        html_data['goods_code'],  # varchar
                        html_data['rotationImgsJson'],  # list
                        set_status_None(html_data['label_ids']),  # varchar
                        html_data['stockNum'],  # int
                        html_data['goods_number'],  # varchar
                        html_data['goods_barCode'],  # varchar
                        html_data['goodsWeight'],  # varchar
                        html_data['goods_volume'],  # varchar
                        html_data['contents'],  # varchar
                        html_data['goodsType'],  # varchar
                        (html_data['distributionType']),
                        html_data['distributionFee'],
                        html_data['goods_sales'] or 0,
                        html_data['sort'] or 0,
                        html_data['rewardIntegral'] or 0,
                        set_status_None(html_data['gift_coupons_id']),
                        set_status_None(html_data['serviceGuarantee_id']),
                        set_status_number(html_data['member_see']),
                        html_data['start_shopping'],
                        set_status_number(html_data['is_limitNum']),
                        html_data['limitNum'],
                        html_data['limitNum_type'],
                        set_status_number(html_data['is_reservation']),
                        set_status_None(html_data['reservation_startTime']) or '2000-01-01 00:00:00',
                        set_status_None(html_data['reservation_endTime']) or '2000-01-01 00:00:00',
                        html_data['reservation_send_time'],
                        set_status_number(html_data['is_reservation_endTime']),
                        set_status_number(html_data['goods_recommend']),
                        set_status_None(html_data['goods_recommend_id']),
                        html_data['keywords'],
                        html_data['goods_introduction'],
                        html_data['goods_distribution_text'],
                        html_data['goods_command'],
                        html_data['goods_recommend_image'],
                        user_id,
                    ))
            else:

                goods_id = Random_id(18, "GOODSID")
                sql = """
                    insert into goods(goodsPrice,goods_status,goodsSkuType,scribePrice,previewUrl,goodsBeginTime,goodsEndingTime,goodsSkuJson,goods_id,goodsName,goods_type,categoryId,businessId,
                        goods_unit,goods_unit_num,goods_code,rotationImgsJson,label_ids,stockNum,goods_number,goods_barCode,goodsWeight,goods_volume,
                        contents,goodsType,distributionType,distributionFee,goods_sales,sort,rewardIntegral,gift_coupons_id,serviceGuarantee_id,member_see,start_shopping,is_limitNum,limitNum
                        ,limitNum_type,is_reservation,reservation_startTime,reservation_endTime,reservation_send_time,is_reservation_endTime,goods_recommend,goods_recommend_id,keywords,goods_introduction,
                        goods_distribution_text,goods_command,goods_recommend_image,merchant_id,ctime
                         ) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now())
                    """
                db.insert(sql, (
                    (html_data['goodsPrice']),  # dict
                    html_data['goods_status'],  # dict
                    html_data['goodsSkuType'],  # dict
                    html_data['scribePrice'],  # dict
                    html_data['previewUrl'],  # dict
                    set_status_None(html_data['goodsBeginTime']) or '2000-01-01 00:00:00',
                    set_status_None(html_data['goodsEndingTime']) or '2000-01-01 00:00:00',
                    html_data['goodsSkuJson'], # dict
                    goods_id, # str
                    html_data['goodsName'], # str
                    set_status_None(html_data['goods_type']), # varchar
                    set_status_None(html_data['categoryId']), # text
                    set_status_None(html_data['businessId']), # text
                    set_status_None(html_data['goods_unit']), # varchar
                    (html_data['goods_unit_num']),  # varchar
                    html_data['goods_code'], # varchar
                    html_data['rotationImgsJson'], # list
                    set_status_None(html_data['label_ids']), # varchar
                    html_data['stockNum'], # int
                    html_data['goods_number'], # varchar
                    html_data['goods_barCode'], # varchar
                    html_data['goodsWeight'],  # varchar
                    html_data['goods_volume'],  # varchar
                    html_data['contents'], # varchar
                    html_data['goodsType'], # varchar
                    (html_data['distributionType']),
                    html_data['distributionFee'],
                    html_data['goods_sales'] or 0,
                    html_data['sort'] or 0,
                    html_data['rewardIntegral'] or 0,
                    set_status_None(html_data['gift_coupons_id']),
                    set_status_None(html_data['serviceGuarantee_id']),
                    set_status_number(html_data['member_see']),
                    html_data['start_shopping'],
                    set_status_number(html_data['is_limitNum']),
                    html_data['limitNum'],
                    html_data['limitNum_type'],
                    set_status_number(html_data['is_reservation']),
                    set_status_None(html_data['reservation_startTime']) or '2000-01-01 00:00:00',
                    set_status_None(html_data['reservation_endTime']) or '2000-01-01 00:00:00',
                    html_data['reservation_send_time'],
                    set_status_number(html_data['is_reservation_endTime']),
                    set_status_number(html_data['goods_recommend']),
                    set_status_None(html_data['goods_recommend_id']),
                    html_data['keywords'],
                    html_data['goods_introduction'],
                    html_data['goods_distribution_text'],
                    html_data['goods_command'],
                    html_data['goods_recommend_image'],
                    user_id,
                ))

            return json({'code': 200, 'message': "添加成功!"})


        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/add', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
class goodsEdit(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表

        client_ip = request.ip
        html_data = request.json
        user_id = request.app.ctx.user_id

        try:

            sql = """
                    update goods set goodsPrice=%s,goods_status=%s,goodsSkuType=%s,scribePrice=%s,previewUrl=%s,goodsBeginTime=%s,goodsEndingTime=%s,goodsSkuJson=%s,goodsName=%s,goods_type=%s,
                    categoryId=%s,businessId=%s,goods_unit=%s,goods_unit_num=%s,goods_code=%s,rotationImgsJson=%s,label_ids=%s,stockNum=%s,goods_number=%s,goods_barCode=%s,goodsWeight=%s,
                    goods_volume=%s, contents=%s,goodsType=%s,distributionType=%s,distributionFee=%s,goods_sales=%s,sort=%s,rewardIntegral=%s,gift_coupons_id=%s,serviceGuarantee_id=%s,
                    member_see=%s,start_shopping=%s,is_limitNum=%s,limitNum=%s,limitNum_type=%s,is_reservation=%s,reservation_startTime=%s,reservation_endTime=%s,reservation_send_time=%s,
                    is_reservation_endTime=%s,goods_recommend=%s,goods_recommend_id=%s,keywords=%s,goods_introduction=%s,goods_distribution_text=%s,goods_command=%s,goods_recommend_image=%s
                    where merchant_id=%s and goods_id=%s
                """

            db.update(sql, (
                (html_data['goodsPrice']),  # dict
                (html_data['goods_status']),  # dict
                html_data['goodsSkuType'],  # dict
                html_data['scribePrice'],  # dict
                html_data['previewUrl'],  # dict
                set_status_None(html_data['goodsBeginTime']) or '2000-01-01 00:00:00',
                set_status_None(html_data['goodsEndingTime']) or '2000-01-01 00:00:00',
                html_data['goodsSkuJson'],  # dict
                html_data['goodsName'],  # str
                set_status_None(html_data['goods_type']),  # varchar
                set_status_None(html_data['categoryId']),  # text
                html_data['businessId'],  # text
                set_status_None(html_data['goods_unit']),  # varchar
                (html_data['goods_unit_num']),  # varchar
                html_data['goods_code'],  # varchar
                html_data['rotationImgsJson'],  # list
                set_status_None(html_data['label_ids']),  # varchar
                html_data['stockNum'],  # int
                html_data['goods_number'],  # varchar
                html_data['goods_barCode'],  # varchar
                html_data['goodsWeight'],  # varchar
                html_data['goods_volume'],  # varchar
                html_data['contents'],  # varchar
                html_data['goodsType'],  # varchar
                (html_data['distributionType']),
                html_data['distributionFee'],
                html_data['goods_sales'] or 0,
                html_data['sort'] or 0,
                html_data['rewardIntegral'] or 0,
                set_status_None(html_data['gift_coupons_id']),
                set_status_None(html_data['serviceGuarantee_id']),
                set_status_number(html_data['member_see']),
                html_data['start_shopping'],
                set_status_number(html_data['is_limitNum']),
                html_data['limitNum'],
                html_data['limitNum_type'],
                set_status_number(html_data['is_reservation']),
                set_status_None(html_data['reservation_startTime']) or '2000-01-01 00:00:00',
                set_status_None(html_data['reservation_endTime']) or '2000-01-01 00:00:00',
                html_data['reservation_send_time'],
                set_status_number(html_data['is_reservation_endTime']),
                set_status_number(html_data['goods_recommend']),
                set_status_None(html_data['goods_recommend_id']),
                html_data['keywords'],
                html_data['goods_introduction'],
                html_data['goods_distribution_text'],
                html_data['goods_command'],
                html_data['goods_recommend_image'],
                user_id,
                html_data['goods_id']
            ))
            return json({'code': 200, 'message': "编辑成功!"})

        except Exception as error:
            # print(error)
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/edit', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
class goodsList(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 10))
        keyword = request.args.get('keyword', '')
        find_user_id = request.args.get('user_id', '')
        store_id = request.args.get('store_id', '')

        try:
            sql = f"""
                    select id,goods_id,businessId,extJson,categoryId,
                goodsSkuJson,goodsPrice,goodsStatus,goodsType,limitNum,goodsName,memberPrice,previewUrl,rewardIntegral,rotationImgsJson,
                scribePrice,stockNum,contents,status,subtitle,ctime,goodsViewCount,paypal_type,distributionFee,
                label_ids,goodsSkuType,goods_type,goods_unit,goods_unit_num,goods_code,goods_status,goods_number,goods_barCode,goods_volume,distributionType,goods_sales,sort,gift_coupons_id,
                serviceGuarantee_id,member_see,start_shopping,reservation_startTime,reservation_endTime,is_reservation,reservation_send_time,is_reservation_endTime,goods_recommend,goods_recommend_id,
                goods_introduction,goods_distribution_text,goods_command,goods_recommend_image
                    from goods where merchant_id='{find_user_id or user_id}'
                """

            tol = f""" SELECT COUNT(*) FROM goods where merchant_id='{find_user_id or user_id}' """

            if store_id:
                sql += f" and  businessId='{store_id}'"
                tol += f" and  businessId='{store_id}'"
            if keyword:
                sql += f" and  goodsName LIKE '%{keyword}%' or subtitle LIKE '%{keyword}%' "
                tol += f" and  goodsName LIKE '%{keyword}%' or subtitle LIKE '%{keyword}%' "
            sql = sqlOrder(sql)
            sql = sqlPaging(pageNum, pageSize, sql)
            tol_data = db.find_one(tol)
            data = db.find_all(sql)
            if data:
                header = ['id', 'goods_id', 'businessId', 'extJson', 'categoryId',
                          'goodsSkuJson', 'goodsPrice', 'goodsStatus', 'goodsType', 'limitNum', 'goodsName',
                          'memberPrice',
                          'previewUrl', 'rewardIntegral', 'rotationImgsJson',
                          'scribePrice', 'stockNum', 'contents', 'status', 'subtitle', 'ctime', 'goodsViewCount',
                          'paypal_type', 'distributionFee',
                          'label_ids', 'goodsSkuType', 'goods_type', 'goods_unit', 'goods_unit_num', 'goods_code', 'goods_status',
                          'goods_number', 'goods_barCode', 'goods_volume', 'distributionType', 'goods_sales', 'sort',
                          'gift_coupons_id',
                          'serviceGuarantee_id', 'member_see', 'start_shopping', 'reservation_startTime', 'reservation_endTime',
                          'is_reservation', 'reservation_send_time', 'is_reservation_endTime', 'goods_recommend',
                          'goods_recommend_id',
                          'goods_introduction', 'goods_distribution_text', 'goods_command', 'goods_recommend_image'

                          ]
                dataList = ProJosn(data, header, 'list')
            else:
                dataList = []
            return json({'code': 200,
                         'data': {
                             'list': dataList,
                             'total': tol_data[0]
                         },
                         'message': "请求成功!"})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
class goodsDelete(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        try:
            sql = "delete from goods where merchant_id=%s and id=%s"

            db.delete(sql, (user_id, html_data['id']))

            return json({'code': 200,
                         'message': "删除成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/delete', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
class goodsDetails(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        goods_id = request.args.get('goods_id')

        try:
            sql = f"""
                select keywords,goodsEndingTime,goodsBeginTime,limitNum_type,is_limitNum,goodsWeight,id,goods_id,businessId,extJson,categoryId,
                goodsSkuJson,goodsPrice,goodsStatus,goodsType,limitNum,goodsName,memberPrice,previewUrl,rewardIntegral,rotationImgsJson,
                scribePrice,stockNum,contents,status,subtitle,ctime,goodsViewCount,paypal_type,distributionFee,
                label_ids,goodsSkuType,goods_type,goods_unit,goods_unit_num,goods_code,goods_status,goods_number,goods_barCode,goods_volume,distributionType,goods_sales,sort,gift_coupons_id,
                serviceGuarantee_id,member_see,start_shopping,reservation_startTime,reservation_endTime,is_reservation,reservation_send_time,is_reservation_endTime,goods_recommend,goods_recommend_id,
                goods_introduction,goods_distribution_text,goods_command,goods_recommend_image
                from goods where merchant_id='{user_id}' and goods_id='{goods_id}'
            """
            data = db.find_all(sql)
            if data:
                header = ['keywords','goodsEndingTime','goodsBeginTime','limitNum_type','is_limitNum','goodsWeight','id', 'goods_id', 'businessId', 'extJson', 'categoryId',
                          'goodsSkuJson', 'goodsPrice', 'goodsStatus', 'goodsType', 'limitNum', 'goodsName',
                          'memberPrice',
                          'previewUrl', 'rewardIntegral', 'rotationImgsJson',
                          'scribePrice', 'stockNum', 'contents', 'status', 'subtitle', 'ctime', 'goodsViewCount',
                          'paypal_type', 'distributionFee',
                          'label_ids', 'goodsSkuType', 'goods_type', 'goods_unit', 'goods_unit_num', 'goods_code', 'goods_status',
                          'goods_number', 'goods_barCode', 'goods_volume', 'distributionType', 'goods_sales', 'sort',
                          'gift_coupons_id',
                          'serviceGuarantee_id', 'member_see', 'start_shopping', 'reservation_startTime', 'reservation_endTime',
                          'is_reservation', 'reservation_send_time', 'is_reservation_endTime', 'goods_recommend',
                          'goods_recommend_id',
                          'goods_introduction', 'goods_distribution_text', 'goods_command', 'goods_recommend_image'

                          ]
                dataList = ProJosn(data, header, 'list')
            else:
                dataList = []
            return json({'code': 200,
                         'data': {
                             'list': dataList
                         },
                         'message': "请求成功!"})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

class businessAdd(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip

        html_data = request.json

        try:
            sql = """
                        insert into business(merchant_id,businessName,businessId,plugsConfigJson,otherConfigJson,status,ctime ) VALUES (%s,%s,%s,%s,%s,%s,now())
                """
            db.insert(sql, (html_data['user_id'],
                            html_data['businessName'],
                            Random_id(32, "B"),
                            html_data['plugsConfigJson'],
                            html_data['otherConfigJson'],
                            set_status(html_data['status']))
                      )
            return json({'code': 200, 'message': "添加成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/business/add', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)


class businessList(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 10))
        keyword = (request.args.get('keyword', ''))
        find_user_id = (request.args.get('user_id', ''))

        try:
            sql = f"""
                    select id,merchant_id,businessName,businessId,plugsConfigJson,otherConfigJson,status,ctime from business where merchant_id='{find_user_id or user_id}'
                """

            # 总数据
            tol = f""" SELECT COUNT(*) FROM  business where merchant_id='{find_user_id or user_id}' """

            # 搜索条件
            if keyword:
                sql += f" and  businessName LIKE '%{keyword}%' "
                tol += f" and  businessName LIKE '%{keyword}%' "

            # 排序
            sql = sqlOrder(sql)
            # 分页pageNum
            sql = sqlPaging(pageNum, pageSize, sql)

            tol_data = db.find_one(tol)

            data = db.find_all(sql)

            if data:
                dataList = ProJosn(data, sql, 'sql')
            else:
                dataList = []

            return json({
                'code': 200,
                'data': {
                    'list': dataList,
                    'total': tol_data[0]
                },
                'message': "请求成功!"
            })

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/business/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)


class businessDel(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        html_data = request.json
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip

        try:
            sql = "delete from business where merchant_id=%s and id=%s"

            db.delete(sql, (html_data['user_id'], html_data['id']))

            return json({'code': 200,
                         'message': "删除成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/business/delete', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
class businessEdit(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip

        html_data = request.json

        sql = """
                update business set plugsConfigJson=%s,otherConfigJson=%s,businessName=%s,status=%s,ctime=now() where merchant_id=%s and id=%s
            """

        db.update(sql, (
            html_data['plugsConfigJson'],
            html_data['otherConfigJson'],
            html_data['businessName'],
            set_status(html_data['status']),
            html_data['user_id'],
            html_data['id']
        ))

        return json({'code': 200, 'message': "编辑成功!"})


class placeAnOrder(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip

        html_data = request.json

        try:
            # 先查询用户
            user_sql = f"""
                select users.nickName,users.openid,users.head_img,users.phone,re.residue from rechargerecord as re 
                JOIN c_users as users on re.openid=users.openid  where re.merchant_id='{user_id}' and re.residue > 0  and users.openid='{html_data['openid']}'
            """
            userData = db.find_all(user_sql)
            titleList = ['nickName', 'openid', 'head_img', 'phone', 'money']

            userData = ProJosn(userData, titleList, 'list', groupType='orderSum')

            # 下单前先排查商品是否是快递  快递得排查地址
            goods_sql = f"""
                select goodsType from goods where merchant_id='{user_id}' and goods_id='{html_data['goods_id']}'
            """
            address_id = ''
            goods_data = db.find_one(goods_sql)
            if goods_data:
                # 判断商品是否是快递
                if goods_data[0] == 1 or goods_data[0] == 5:
                    address_sql = f"""
                        select id from user_address where merchant_id='{user_id}' and openid='{html_data['openid']}' and user_use=1
                    """
                    address_data = db.find_one(address_sql)
                    if address_data:
                        address_id = address_data[0]
                    else:
                        return json({'code': 201, 'message': "请填写您得收货地址再购买!"})
                else:
                    pass
            else:
                return json({'code': 201, 'message': "未找到该商品!"})

            goodsPrice = float(html_data['goodsPrice'])  # 商品价格
            if len(userData):
                userData = userData[0]

                # 判断商品价格是否大于余额
                if userData['money'] >= goodsPrice:
                    rechargerecord_sql = f"""
                        select residue,id from rechargerecord where openid='{userData['openid']}' and residue>0
                    """

                    money_sql = f"""
                        select sum(residue) as money from rechargerecord where openid='{userData['openid']}' and residue>0
                    """
                    money = db.find_one(money_sql)[0]

                    rechargerecord = db.find_all(rechargerecord_sql)
                    rechargerecord = ProJosn(rechargerecord, rechargerecord_sql)

                    if money >= goodsPrice:

                        for i in rechargerecord:

                            if goodsPrice <= (i['residue']):

                                recharge_sql = f"""
                                    update rechargerecord set residue=%s,paymentStatus=%s where id='{i['id']}'
                                """
                                if i['residue'] - goodsPrice > 0:
                                    paymentStatus = '1'
                                    goodsPrice = i['residue'] - goodsPrice
                                else:
                                    paymentStatus = '4'
                                    goodsPrice = goodsPrice - i['residue']
                                db.update(recharge_sql, (
                                    goodsPrice,
                                    paymentStatus
                                ))

                                # 生成订单
                                order_id = Random_id(32, 'ORDER')
                                order_sql = f"""
                                    insert into goods_order(goodsQuantity,merchant_id,order_id,address_id,business_id,wechat_openid,wechatNickname,wechatavatar,wechatphone,goods_id,order_type,paypal_type,total_money,
                                        goods_money,payStatus,utime,ctime) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now(),now())
                                """
                                db.insert(order_sql, (
                                    1,
                                    user_id,
                                    order_id,
                                    address_id,
                                    html_data['businessId'],
                                    html_data['openid'],
                                    html_data['nickName'],
                                    html_data['head_img'],
                                    html_data['phone'],
                                    html_data['goods_id'],
                                    html_data['order_type'],
                                    html_data['paypal_type'],
                                    float(html_data['goodsPrice']),
                                    float(html_data['goodsPrice']),
                                    '3'
                                ))

                                return json({'code': 200, 'message': "请求成功!"})
                            elif goodsPrice > i['residue']:
                                goodsPrice = goodsPrice - i['residue']
                                if goodsPrice > 0:
                                    recharge_sql = f"""
                                        update rechargerecord set residue=%s,paymentStatus=%s where id='{i['id']}'
                                    """
                                    db.update(recharge_sql, (
                                        0,
                                        '4'
                                    ))
                                else:
                                    return json({'code': 201, 'message': "余额不足!"})
                            else:
                                return json({'code': 201, 'message': "余额不足!"})
                    else:
                        return json({'code': 201, 'message': "余额不足!"})
                else:
                    return json({'code': 201, 'message': "余额不足!"})
            else:
                return json({'code': 201, 'message': "用户不存在!"})

            # return json({'code': 200, 'message': "下单成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/order/placeAnOrder', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)


class orderList(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 10))
        keyword = (request.args.get('keyword', ''))

        try:
            sql = f"""
                   select goods_order.coupon_id,goods_order.memo,goods_order.business_info,goods_order.address_id,goods_order.user_info,goods_order.goods_info,goods_order.goodsQuantity,goods_order.payStatus,goods_order.id,goods_order.order_id,goods_order.business_id,goods_order.wechat_openid,goods_order.wechatNickname,goods_order.wechatavatar,goods_order.wechatphone,
                    goods_order.goods_id,goods_order.goods_sku,goods_order.order_type,goods_order.paypal_type,goods_order.distribution_type,goods_order.total_money,
                    goods_order.goods_money,goods_order.utime,goods_order.ctime,goods_order.paypalDetails,goods.goodsName,goods.previewUrl from goods_order 
                    JOIN goods on goods_order.goods_id=goods.goods_id where goods_order.merchant_id='{user_id}'
                """
            # 总数据
            tol = f""" SELECT COUNT(*) from goods_order 
                    JOIN goods on goods_order.goods_id=goods.goods_id where goods_order.merchant_id='{user_id}' """

            # 搜索条件
            if keyword:
                sql += f" and  goods_order.goods_id LIKE '%{keyword}%' or goods_order.business_id LIKE '%{keyword}%' or goods_order.order_id LIKE '%{keyword}%' or goods_order.wechat_openid LIKE '%{keyword}%' or goods_order.wechatNickname LIKE '%{keyword}%' "
                tol += f" and  goods_order.goods_id LIKE '%{keyword}%' or goods_order.business_id LIKE '%{keyword}%' or goods_order.order_id LIKE '%{keyword}%' or goods_order.wechat_openid LIKE '%{keyword}%' or goods_order.wechatNickname LIKE '%{keyword}%' "

            sql = sqlOrder(sql, 'utime')

            sql = sqlPaging(pageNum, pageSize, sql)

            title_list = ['coupon_id','memo','business_info','address_id','user_info','goods_info','goodsQuantity', 'payStatus', 'id', 'order_id', 'business_id', 'wechat_openid',
                          'wechatNickname', 'wechatavatar', 'wechatphone', 'goods_id', 'goods_sku', 'order_type',
                          'paypal_type',
                          'distribution_type', 'total_money', 'goods_money', 'utime', 'ctime', 'paypalDetails',
                          'goodsName', 'previewUrl'
                          ]
            data = db.find_all(sql)

            tol_data = db.find_one(tol)

            if data:
                dataList = ProJosn(data, title_list, 'list')
            else:
                dataList = []

            return json({
                'code': 200,
                'data': {
                    'list': dataList,
                    'total': tol_data[0]
                },
                'message': "请求成功!"
            })

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/order/list', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)


class orderEdit(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表

        client_ip = request.ip
        html_data = request.json
        user_id = request.app.ctx.user_id
        # print(html_data)
        try:

            sql = """
                    update goods_order set payStatus=%s,utime=now()
                    where merchant_id=%s and id=%s
                """

            db.update(sql, (
                html_data['payStatus'],
                user_id,
                html_data['id']
            ))
            log = ''
            # 1.确认订单,2.支付中,3.已支付,4.待发货,5.已发货,6.待收货,7.已收货,8.已退款,0.待支付
            if html_data['payStatus'] == 0:
                log ='待支付'
            if html_data['payStatus'] == 1:
                log ='确认订单'
            if html_data['payStatus'] == 2:
                log ='支付中'
            if html_data['payStatus'] == 3:
                log ='已支付'
            if html_data['payStatus'] == 4:
                log ='待发货'
            if html_data['payStatus'] == 5:
                log ='已发货'
            if html_data['payStatus'] == 6:
                log ='待收货'
            if html_data['payStatus'] == 7:
                log ='已收货'
            if html_data['payStatus'] == 8:
                log ='已退款'

            # 操作日志
            order_log(db, {
                'merchant_id': user_id,
                'order_id': html_data['order_id'],
                'order_log': f'后台管理操作:'+log,
                'content': '后台管理操作',
                'goods_info': '',
                'user_info': jn.dumps({'user_id':user_id}),
                'type': 'pc后台',
                'payStatus': html_data['payStatus'],
                'openid': '',
                'order_info': ''
            })

            return json({'code': 200, 'message': "编辑成功!"})

        except Exception as error:
            # print(error)
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/edit', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)


class orderDel(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        try:
            sql = "delete from goods_order where merchant_id=%s and id=%s"

            db.delete(sql, (user_id, html_data['id']))

            return json({'code': 200,
                         'message': "删除成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/order/delete', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)


class orderDetails(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        pageNum = 1
        pageSize = 2
        html_data = request.json

        try:
            sql = f"""
               select goods_order.coupon_id,goods_order.memo,goods_order.business_info,goods_order.address_id,goods_order.user_info,goods_order.goods_info,goods_order.goodsQuantity,goods_order.address_id,goods_order.payStatus,goods_order.id,goods_order.order_id,goods_order.business_id,goods_order.wechat_openid,goods_order.wechatNickname,goods_order.wechatavatar,goods_order.wechatphone,
                goods_order.goods_id,goods_order.goods_sku,goods_order.order_type,goods_order.paypal_type,goods_order.distribution_type,goods_order.total_money,
                goods_order.goods_money,goods_order.utime,goods_order.ctime,goods_order.paypalDetails,goods.goodsName,goods.previewUrl from goods_order 
                JOIN goods on goods_order.goods_id=goods.goods_id where goods_order.merchant_id='{user_id}' and goods_order.id={html_data['id']}
            """

            # 搜索条件
            # if keyword:
            #     sql += f" and  goods_order.goods_id LIKE '%{keyword}%' or goods_order.business_id LIKE '%{keyword}%' or goods_order.order_id LIKE '%{keyword}%' or goods_order.wechat_openid LIKE '%{keyword}%' or goods_order.wechatNickname LIKE '%{keyword}%' "
            #     tol += f" and  goods_order.goods_id LIKE '%{keyword}%' or goods_order.business_id LIKE '%{keyword}%' or goods_order.order_id LIKE '%{keyword}%' or goods_order.wechat_openid LIKE '%{keyword}%' or goods_order.wechatNickname LIKE '%{keyword}%' "

            title_list = ['coupon_id','memo','business_info','address_id','user_info','goods_info','goodsQuantity', 'address_id', 'payStatus', 'id', 'order_id', 'business_id', 'wechat_openid',
                          'wechatNickname', 'wechatavatar', 'wechatphone', 'goods_id', 'goods_sku', 'order_type',
                          'paypal_type',
                          'distribution_type', 'total_money', 'goods_money', 'utime', 'ctime', 'paypalDetails',
                          'goodsName', 'previewUrl']
            data = db.find_all(sql)

            if data:
                dataList = ProJosn(data, title_list, 'list')
            else:
                dataList = []

            return json({
                'code': 200,
                'data': {
                    'list': dataList,
                },
                'message': "请求成功!"
            })

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/order/orderDetails', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

class order_logs(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        order_id = (request.args.get('order_id', ''))

        try:
            sql = f"""
               select order_log,content,type,user_info,goods_info,ctime,payStatus,openid,user_id,order_info from order_log where merchant_id='{user_id}' and order_id='{order_id}'
            """

            data = db.find_all(sql)
            if data:
                dataList = ProJosn(data,sql)
            else:
                dataList = []

            return json({
                'code': 200,
                'data': {
                    'list': dataList,
                },
                'message': "请求成功!"
            })

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/order_log', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

# 商品标签列表
class goodsLabelList(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表

        client_ip = request.ip
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 10))
        keyword = request.args.get('keyword', '')
        user_id = request.args.get('user_id', '') or request.app.ctx.user_id
        group_id = int(request.args.get('group_id', '0'))
        try:
            sql = f"""
                        select id,labelName,labelType,labelGrounpId,useType,setting,fontColor,backgroundColor,borderColor,sort,ctime,status from goods_label where merchant_id='{user_id}'
                    """

            tol = f""" SELECT COUNT(*) FROM goods_label where merchant_id='{user_id}' """
            if group_id != 0:
                sql += f' and labelGrounpId={group_id} '
                tol += f' and labelGrounpId={group_id} '

            if keyword:
                sql += f" and  labelName LIKE '%{keyword}%' "
                tol += f" and  labelName LIKE '%{keyword}%' "
            tol_data = db.find_one(tol)

            ordersql = sqlOrder(sql)
            group_sql = sqlPaging(pageNum, pageSize, ordersql)
            data = db.find_all(group_sql)
            if data:
                dataList = ProJosn(data, sql, 'sql')
            else:
                dataList = []
            return json({'code': 200,
                         'data': {
                             'list': dataList,
                             'total': tol_data[0]
                         },
                         'message': "请求成功!"})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/goodsLabelList', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
#商品标签添加
class goodsLabelAdd(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        try:
            if html_data['labelGrounpId']:
                for i in html_data['labelGrounpId']:
                    sql = "insert into goods_label(merchant_id,labelName,labelType,labelGrounpId,useType,setting,fontColor,backgroundColor,borderColor,sort,image,status,ctime) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now())"
                    db.insert(sql, (
                        user_id,
                        html_data['labelName'],
                        html_data['labelType'],
                        i,
                        html_data['useType'],
                        html_data['setting'],
                        html_data['fontColor'],
                        html_data['backgroundColor'],
                        html_data['borderColor'],
                        html_data['sort'],
                        html_data['image'],
                        set_status(html_data['status']),
                    ))
            else:
                return json({'code': 500,
                             'message': "缺少分组id!"})

            return json({'code': 200,
                         'message': "添加成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/goodsLabelAdd', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
# 商品标签删除
class goodsLabelDel(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        try:
            sql = "delete from goods_label where merchant_id=%s and id=%s"

            db.delete(sql, (user_id, html_data['id']))

            return json({'code': 200,
                         'message': "删除成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/goods_label', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
# 商品标签编辑
class goodsLabelEdit(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip

        html_data = request.json

        try:
            sql = """
                    update goods_label set image=%s,labelName=%s,labelType=%s,labelGrounpId=%s,useType=%s,setting=%s,fontColor=%s,backgroundColor=%s,borderColor=%s,sort=%s,status=%s where merchant_id=%s and id=%s
                """
            db.update(sql,(
                html_data['image'],
                html_data['labelName'],
                html_data['labelType'],
                html_data['labelGrounpId'],
                html_data['useType'],
                html_data['setting'],
                html_data['fontColor'],
                html_data['backgroundColor'],
                html_data['borderColor'],
                html_data['sort'],
                set_status(html_data['status']),
                user_id,
                html_data['id']
            ))
            return json({'code': 200,
                        'message': "编辑成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/goodsLabelEdit', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)

# 商品分组标签列表
class goodsGroupList(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表

        client_ip = request.ip
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 10))
        keyword = request.args.get('keyword', '')
        user_id = request.args.get('user_id', '') or request.app.ctx.user_id
        try:
            sql = f"""
                        select id,groupName,sort,ctime from goodLabelGroup where merchant_id='{user_id}'
                    """
            tol = f""" SELECT COUNT(*) FROM goodLabelGroup where merchant_id='{user_id}' """

            if keyword:
                sql += f" and  groupName LIKE '%{keyword}%' "
                tol += f" and  groupName LIKE '%{keyword}%' "
            tol_data = db.find_one(tol)
            ordersql = sqlOrder(sql)
            group_sql = sqlPaging(pageNum, pageSize, ordersql)
            data = db.find_all(group_sql)
            if data:
                dataList = ProJosn(data, sql, 'sql')
            else:
                dataList = []
            return json({'code': 200,
                         'data': {
                             'list': dataList,
                             'total': tol_data[0]
                         },
                         'message': "请求成功!"})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/goodsGroupList', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
#商品分组标签添加
class goodsGroupAdd(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        try:
            sql = "insert into goodLabelGroup(groupName,sort,merchant_id,ctime) VALUES(%s,%s,%s,now())"

            db.insert(sql, (
                html_data['groupName'],
                html_data['sort'],
                user_id,
            ))

            return json({'code': 200,
                         'message': "添加成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/goodsGroupAdd', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
# 商品分组标签删除
class goodsGroupDel(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        try:
            sql = "delete from goodLabelGroup where merchant_id=%s and id=%s"

            db.delete(sql, (user_id, html_data['id']))

            return json({'code': 200,
                         'message': "删除成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/goodsGroupDel', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
# 商品标签编辑
class goodsGroupEdit(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip

        html_data = request.json

        try:
            sql = """
                    update goodLabelGroup set groupName=%s,sort=%s where merchant_id=%s and id=%s
                """
            db.update(sql,(
                html_data['groupName'],
                html_data['sort'],
                user_id,
                html_data['id'],
            ))
            return json({'code': 200,
                        'message': "编辑成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/goodsGroupEdit', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)

# 商品标签分组查询
class goodsLabelOptions(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表

        client_ip = request.ip
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 100))
        group_id = int(request.args.get('group_id', '0'))

        user_id = request.args.get('user_id', '') or request.app.ctx.user_id
        try:
            sql = f"""
                    select id,labelName,labelType,labelGrounpId,useType,setting,fontColor,backgroundColor,borderColor,sort,ctime,status from goods_label where merchant_id='{user_id}' 
                """
            if group_id != 0:
                sql += f' and labelGrounpId={group_id} '

            ordersql = sqlOrder(sql)
            group_sql = sqlPaging(pageNum, pageSize, ordersql)
            data = db.find_all(group_sql)
            if data:
                dataList = ProJosn(data, sql, 'sql')
            else:
                dataList = []
            return json({'code': 200,
                         'data': {
                             'list': dataList,
                         },
                         'message': "请求成功!"})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/goodsLabelOptions', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

# 商品规格模版列表
class goodsSkuTemplateList(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表

        client_ip = request.ip
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 10))
        keyword = request.args.get('keyword', '')
        user_id = request.args.get('user_id', '') or request.app.ctx.user_id
        try:
            sql = f"""
                        select id,content,goods_sku,goods_attribute,templateName,ctime from goods_sku_template where merchant_id='{user_id}'
                    """
            tol = f""" SELECT COUNT(*) FROM goods_sku_template where merchant_id='{user_id}' """

            if keyword:
                sql += f" and  content LIKE '%{keyword}%' "
                tol += f" and  content LIKE '%{keyword}%' "
            tol_data = db.find_one(tol)
            ordersql = sqlOrder(sql)
            group_sql = sqlPaging(pageNum, pageSize, ordersql)
            data = db.find_all(group_sql)
            if data:
                dataList = ProJosn(data, sql, 'sql')
            else:
                dataList = []
            return json({'code': 200,
                         'data': {
                             'list': dataList,
                             'total': tol_data[0]
                         },
                         'message': "请求成功!"})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/goodsSkuTemplateList', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
#商品规格模版添加
class goodsSkuTemplateAdd(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        try:
            sql = "insert into goods_sku_template(templateName,content,goods_sku,goods_attribute,status,merchant_id,ctime) VALUES(%s,%s,%s,%s,%s,%s,now())"
            db.insert(sql, (
                html_data['templateName'],
                html_data['content'],
                html_data['goods_sku'],
                html_data['goods_attribute'],
                html_data['status'],
                user_id,
            ))
            return json({'code': 200,
                         'message': "添加成功!"})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/goodsSkuTemplateAdd', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
# 商品规格模版删除
class goodsSkuTemplateDel(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        try:
            sql = "delete from goods_sku_template where merchant_id=%s and id=%s"

            db.delete(sql, (user_id, html_data['id']))

            return json({'code': 200,
                         'message': "删除成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/goodsSkuTemplateDel', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

# 商品规格模版详情
class goodsSkuTemplateDetails(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表

        client_ip = request.ip
        pageNum = int(request.args.get('pageNum', 1))
        pageSize = int(request.args.get('pageSize', 10))
        ids = request.args.get('id', 0)
        keyword = request.args.get('keyword', '')
        user_id = request.args.get('user_id', '') or request.app.ctx.user_id

        try:
            sql = f"""
                        select id,content,goods_sku,goods_attribute,templateName,ctime from goods_sku_template where merchant_id='{user_id}' and id={ids}
                    """
            tol = f""" SELECT COUNT(*) FROM goods_sku_template where merchant_id='{user_id}' and id={ids} """

            if keyword:
                sql += f" and  templateName LIKE '%{keyword}%' "
                tol += f" and  templateName LIKE '%{keyword}%' "
            tol_data = db.find_one(tol)
            ordersql = sqlOrder(sql)
            group_sql = sqlPaging(pageNum, pageSize, ordersql)
            data = db.find_all(group_sql)
            if data:
                dataList = ProJosn(data, sql, 'sql')
            else:
                dataList = []
            return json({'code': 200,
                         'data': {
                             'list': dataList,
                             'total': tol_data[0]
                         },
                         'message': "请求成功!"})
        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/goodsSkuTemplateDetails', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)


class useCoupons(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip

        openid = (request.args.get('openid', ''))
        coupons_id = request.args.get('coupons_id', 0)
        try:
            sql = f"""
                select my_coupons.coupons_id,coupons.title,coupons.type,coupons.score,coupons.moneys,coupons.content,coupons.businessId,coupons.status,coupons.item_id,coupons.item_dict,goods_id,my_coupons.status
                from my_coupons join coupons on my_coupons.coupons_id=coupons.id where my_coupons.merchant_id='{user_id}' and my_coupons.openid='{openid}' and my_coupons.id={coupons_id}
            """

            header_data = ['coupons_id','title','type','score','moneys','content','businessId','c_status','item_id','item_dict','goods_id','my_status']
            data = db.find_all(sql)

            data = ProJosn(data,header_data,'list')

            return json({'code': 200, 'message': "请求成功!",'data':{
                'list':data,
            }})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/useCoupons', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)